# -*- coding: utf-8 -*-

# A demo scheduler.py

import pyb


class Scheduler:
    def __init__(self):
        self.events = []

    def schedule(self, delay, function):
        if delay <= 0:
            function()
        else:
            self.events.append([delay, function])
            self.events.sort(key=lambda event: event[0])

    def run(self):
        while len(self.events) > 0:
            delay, function = self.events.pop(0)
            for event in self.events:
                event[0] -= delay
            pyb.delay(delay)
            function()


def job1():
    pyb.LED(1).toggle()
    sched.schedule(1000, job2)


def job2():
    pyb.LED(2).toggle()
    sched.schedule(2000, job1)


sched = Scheduler()
job1()
job2()
sched.run()